package com.cho3.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cho3.R;
import com.cho3.costant.Constant;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.leo618.zip.IZipCallback;
import com.leo618.zip.ZipManager;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

public abstract class UpdateDialog extends Dialog {
    private View contentView;
    private TextView updateInfo;
    private NumberProgressBar progressBar;
    private TextView stateInfo;
    private TextView tvConfirm;
    private String downloadFileUrl;
    private Context mContext;
    private String mJsBundleVersion;

    public UpdateDialog(@NonNull Context context, String downLoadFileUrl, String jsBundleVersion) {
        super(context, R.style.dialogStyle);
        this.mContext = context;
        this.downloadFileUrl = downLoadFileUrl;
        this.mJsBundleVersion = jsBundleVersion;
        contentView = LayoutInflater.from(context).inflate(R.layout.dialog_update, null);
        setContentView(contentView);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.width = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.6);
        getWindow().setAttributes(params);
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        initView(contentView);
        tvConfirm.setEnabled(true);
        stateInfo.setVisibility(View.GONE);
        progressBar.setVisibility(View.INVISIBLE);
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downLoadFile(downLoadFileUrl);
            }
        });
    }

    /**
     * 下载文件
     *
     * @param downLoadFileUrl
     */
    private void downLoadFile(String downLoadFileUrl) {
        progressBar.setVisibility(View.VISIBLE);
        tvConfirm.setEnabled(false);
        stateInfo.setVisibility(View.VISIBLE);
        stateInfo.setText("下载资源中...");
        File zipFile = new File(Constant.getBundleZipPath(mContext));
        if (FileUtils.isFileExists(zipFile)) {
            FileUtils.delete(zipFile);
        }
        File unZipFile = new File(Constant.getBundleZipPath(mContext));
        if (FileUtils.isDir(unZipFile)) {
            FileUtils.delete(unZipFile);
        }
        FileDownloader.getImpl().create(downLoadFileUrl)
                .setPath(Constant.getBundleZipPath(mContext))
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        double percent = soFarBytes * 1.0 / totalBytes;
                        Log.i("main1", percent + "");
                        int progress = (int) (percent * 100);
                        progressBar.setProgress(progress);
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        ToastUtils.showShort("下载成功");
                        File zipFile = new File(Constant.getBundleZipPath(mContext));
                        String zipPath = Constant.getBundleZipPath(mContext);
                        String unzipPath = Constant.getBundleUnZipPath(mContext);
                        if (FileUtils.isFileExists(zipFile)) {
                            ZipManager.unzip(zipPath, unzipPath, new IZipCallback() {
                                @Override
                                public void onStart() {
                                    stateInfo.setText("资源解压中....");
                                    progressBar.setProgress(0);
                                }

                                @Override
                                public void onProgress(int percentDone) {
                                    progressBar.setProgress(percentDone);
                                }

                                @Override
                                public void onFinish(boolean success) {
                                    if (success) {
                                        stateInfo.setText("解压完成,资源加载中");
                                        ToastUtils.showShort("解压完成，资源加载中...");
                                        CacheDiskUtils.getInstance().put("js_bundle_version", mJsBundleVersion);
                                        jumpToMain(true);
                                        dismiss();
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        ToastUtils.showShort("下载出错");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }

    public abstract void jumpToMain(boolean isGoTo);

    private void initView(View contentView) {
        updateInfo = contentView.findViewById(R.id.tv_update_info);
        progressBar = contentView.findViewById(R.id.progressbar);
        stateInfo = contentView.findViewById(R.id.tv_state_info);
        tvConfirm = contentView.findViewById(R.id.tv_confirm);
    }
}
